package com.qf.dao.impl;

import com.qf.dao.AddressDao;
import com.qf.domain.Address;
import com.qf.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class AddressDaoImpl implements AddressDao {
    private QueryRunner queryRunner=new QueryRunner(DataSourceUtil.getDataSource());
    @Override
    public List<Address> findByUserId(Integer uid) {
        String sql=" SELECT `id`,`detail`,`name`,`phone`,`uid`,`level` FROM `tb_address` WHERE `uid`=? ";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Address.class), uid);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void addAddress(Address address) {
        String sql=" INSERT INTO `tb_address` (`detail`,`name`,`phone`,`uid`,`level`) VALUES (?,?,?,?,?);\n ";
        Object [] params={address.getDetail(),address.getName(),address.getPhone(),address.getUid(),address.getLevel()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void moveById(Integer uid, int aid) {
        String sql=" DELETE FROM `tb_address` WHERE `id`=?  AND `uid`=? ";
        try {
            queryRunner.update(sql,aid,uid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void setDefault(Integer uid, int aid) {
        String sql1=" UPDATE `tb_address` SET `level` =0 WHERE `uid`=? ";
        String sql2=" UPDATE `tb_address` SET `level` =1 WHERE `uid`=? AND `id`=?";
        try {
            queryRunner.update(sql1,uid);
            queryRunner.update(sql2,uid,aid);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void modifyAddress(Address address) {
        String sql=" UPDATE `tb_address` SET `detail`=?,`name`=?,`phone`=?,`level`=? WHERE `id`=? AND `uid`=? ";
        Object[] params={address.getDetail(),address.getName(),address.getPhone(),address.getLevel(),address.getId(),address.getUid()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public void removeByUId(int uid) {
        String sql=" DELETE FROM `tb_address` WHERE AND `uid`=? ";
        try {
            queryRunner.update(sql,uid);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
